<template>
  <div class="bill-detail-mobile common-mobile-view">
    <el-form ref="formRef" :model="billStore.currentBillRecord"
             :rules="rules" label-width="80px">
      <el-form-item label="账本类型" prop="bookName">
        <el-radio-group v-model="billStore.currentBillRecord.bookName"
                        @change="changeBillBookNameEvent">
          <el-radio v-for="(item, index) in billStore.billBookList"
                    :value="item.name" :key="index">
            <template #default>
              <i :class="item.icon" :style="{color: item.color}"/>
              <span style="margin-left: 5px;">{{ item.name }}</span>
            </template>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账单类别" prop="type">
        <el-radio-group v-model="billStore.currentBillRecord.type"
                        @change="changeBillCategoryEvent">
          <el-radio v-for="(item, index) in billInfo.billTypeList"
                    :value="item" :key="index">
            {{ getBillTypeName(item) }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账单分类" prop="category">
        <el-radio-group v-model="billStore.currentBillRecord.category">
          <el-radio v-for="(item, index) in billInfo.billCategoryList"
                    :value="item.name" :key="index">
            <template #default>
              <i :class="item.icon" :style="{color: item.color}"/>
              <span style="margin-left: 5px;">{{ item.name }}</span>
            </template>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账单时间" prop="date">
        <el-date-picker
            v-model="billStore.currentBillRecord.date"
            type="date" :editable="false" placeholder="请选择账单时间"
            value-format="YYYY-MM-DD"/>
      </el-form-item>

      <el-form-item label="账单地点" prop="location">
        <el-input v-model="billStore.currentBillRecord.location" autocomplete="off"
                  placeholder="请输入账单地点"  clearable
                  show-word-limit maxlength="10">
          <template #prefix>
            <el-icon class="el-input__icon"><location/></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="账单账户" prop="payAccount">
        <el-radio-group v-model="billStore.currentBillRecord.payAccount">
          <el-radio v-for="(item, index) in billStore.billPayList"
                    :value="item.name" :key="index">
            <template #default>
              <i :class="item.icon" :style="{color: item.color}"/>
              <span style="margin-left: 5px;">{{ item.name }}</span>
            </template>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账单金额" prop="amount">
        <amount-input v-model="billStore.currentBillRecord.amount"/>
      </el-form-item>

      <el-form-item label="账单内容" prop="content">
        <el-input v-model="billStore.currentBillRecord.content" autocomplete="off"
                  placeholder="请输入账单内容"  clearable
                  show-word-limit maxlength="10">
          <template #prefix>
            <el-icon class="el-input__icon"><document/></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="账单备注">
        <el-input v-model="billStore.currentBillRecord.remark" type="textarea"
                  placeholder="请输入账单备注" clearable
                  :rows="5" show-word-limit maxlength="200">
        </el-input>
      </el-form-item>

      <el-form-item label="账单图片">
        <upload-image v-model="billStore.currentBillRecord.imageList"
                      :service-url="fileServiceUrl"
                      :service-file-root-path="serviceFileRootPath"
                      :image-path="billStore.billImagePath"/>
      </el-form-item>
    </el-form>

    <div class="button-container">
      <el-button type="primary" @click="confirmClick">确认</el-button>
      <el-button v-if="billStore.billApiType === 'UPDATE'"
                 type="danger" @click="deleteClick">删除</el-button>
      <el-button type="info" @click="cancelClick">取消</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { UploadImage, AmountInput } from 'vue3-common'
import { useBillStore } from '@/store/bill.ts'
import { useAppStore } from '@/store/app.ts'
import { Location, Document } from '@element-plus/icons-vue'
import { FormRules } from 'element-plus'
import { billRecordRules } from '@/utils/element/elRules.ts'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { IBillCategory } from '@/types/bill.ts'
import { commonElMessageBox } from 'vue3-common/utils/elUtil'
import { fileServiceUrl, serviceFileRootPath } from '@/utils'

const formRef = ref()
const rules = reactive<FormRules>(billRecordRules)
const billStore = useBillStore()
const appStore = useAppStore()

const billInfo = reactive({
  billTypeList: [] as string[],
  billCategoryList: [] as IBillCategory[]
})

onMounted(async () => {
  appStore.isShowMobileBack = true

  await billStore.initBillInfo()
  await initBillRecord()
})

const initBillRecord = async () => {
  // 如果是新增账单 默认选择第一个账本
  if (billStore.billApiType !== 'UPDATE') {
    billStore.currentBillRecord.bookName = billStore.billBookList[0].name
  }
  getBillTypeByBookName(billStore.currentBillRecord.bookName)

  // 如果是新增账单 默认选择一个类别
  if (billStore.billApiType !== 'UPDATE') {
    billStore.currentBillRecord.type = billInfo.billTypeList[0]
  }
  getBillCategory()

  // 如果是新增账单 默认选择一个分类
  if (billStore.billApiType !== 'UPDATE') {
    billStore.currentBillRecord.category = billInfo.billCategoryList[0].name
    billStore.currentBillRecord.payAccount = billStore.billPayList[0].name
  }

  await nextTick(() => {
    formRef.value.clearValidate()
  })
}

/**
 * 获取账单类型名称
 * @param type 账单类型
 */
const getBillTypeName = (type: string) => {
  return type === 'expensive' ? '支出' : '收入'
}

/**
 * 选择账本事件
 * @param value 账本名称
 */
const changeBillBookNameEvent = (value: string) => {
  getBillTypeByBookName(value)
  billStore.currentBillRecord.type = billInfo.billTypeList[0]
  getBillCategory()
  billStore.currentBillRecord.category = billInfo.billCategoryList[0].name
}

/**
 * 选择账单类别事件
 */
const changeBillCategoryEvent = () => {
  getBillCategory()
  billStore.currentBillRecord.category = billInfo.billCategoryList[0].name
}

/**
 * 通过账本获取账单类型
 * @param bookName 账本
 */
const getBillTypeByBookName = (bookName: string) => {
  billInfo.billTypeList = []
  billStore.billCategoryList.forEach((item) => {
    if (item.bookName === bookName && !billInfo.billTypeList.includes(item.type)) {
      billInfo.billTypeList.push(item.type)
    }
  })
}

/**
 * 获取账单类别
 */
const getBillCategory = () => {
  billInfo.billCategoryList = billStore.billCategoryList.filter((value) => {
    return value.bookName === billStore.currentBillRecord.bookName
        && value.type === billStore.currentBillRecord.type
  })
}

/**
 * 点击确认按钮
 */
const confirmClick = () => {
  formRef.value.validate().then(async () => {
    await billStore.handleBillApi(billStore.currentBillRecord)
    history.back()
  })
}

const cancelClick = () => {
  history.back()
}

const deleteClick = () => {
  commonElMessageBox('是否确认删除该账单内容?').then(async () => {
    billStore.billApiType = 'DELETE'
    await billStore.handleBillApi(billStore.currentBillRecord)
    history.back()
  })
}
</script>

<style scoped lang="scss">
.bill-detail-mobile {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .button-container {
    align-self: center;
  }
}
</style>
